package com.hu.bgp.client.eventservice;

import de.novanic.eventservice.client.event.RemoteEventService;
import de.novanic.eventservice.client.event.RemoteEventServiceFactory;

/**
 * Stub nodig om eigen klassen te instantieren in getRemoteEventService() om te
 * compenseren voor de tekortkomingen van gwteventservice.
 * 
 * @author ejvos
 */
public class BgpRemoteEventServiceFactory
{
	private volatile RemoteEventService myRemoteEventService;

	/**
	 * The RemoteEventServiceFactory should be created via the getInstance
	 * method.
	 * 
	 * @see RemoteEventServiceFactory#getInstance()
	 */
	private BgpRemoteEventServiceFactory()
	{
	}

	/**
	 * Factory-Holder class to ensure thread-safe lazy-loading with IODH.
	 */
	private static class RemoteEventServiceFactoryHolder
	{
		private static BgpRemoteEventServiceFactory INSTANCE = createRemoteEventServiceFactory();
	}

	/**
	 * This method should be used to create an instance of
	 * RemoteEventServiceFactory. RemoteEventServiceFactory is a singleton, so
	 * this method returns always the same instance of
	 * RemoteEventServiceFactory.
	 * 
	 * @return RemoteEventServiceFactory (singleton)
	 */
	public static BgpRemoteEventServiceFactory getInstance()
	{
		return RemoteEventServiceFactoryHolder.INSTANCE;
	}

	/**
	 * This method should be used to create an instance of RemoteEventService.
	 * RemoteEventService is a singleton, so this method returns always the same
	 * instance of RemoteEventService. The session is needed to generate the
	 * client/user id.
	 * 
	 * @return RemoteEventService (singleton)
	 */
	public RemoteEventService getRemoteEventService()
	{
		if (myRemoteEventService == null)
		{
			synchronized (this)
			{
				if (myRemoteEventService == null)
				{
					myRemoteEventService = new BgpRemoteEventService(new BgpRemoteEventConnector());
				}
			}
		}
		return myRemoteEventService;
	}

	private static BgpRemoteEventServiceFactory createRemoteEventServiceFactory()
	{
		return new BgpRemoteEventServiceFactory();
	}

	/**
	 * That method should only be used in TestCases, because it resets the
	 * factory and the factory can't ensure anymore that only one instance
	 * exists!
	 */
	public static void reset()
	{
		RemoteEventServiceFactoryHolder.INSTANCE = createRemoteEventServiceFactory();
	}
}
